/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.hamacekj.dotaznikserver;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

/**
 * Otázka s výběrem několika vzájemně se vylučujících možností.
 * @author Jan Hamáček
 */
public class RadioQuestion implements Question {

    public RadioQuestion() {
        this.tableModel.addColumn("Počítač");
        this.tableModel.addColumn("Odpověď");
    }
    
    public RadioQuestion(int id, String message){
        this();
        this.id = id;
        this.message = message;
    }
    
    public void addOption(String option){
        this.options.add(new Option(options.size(), option));
    }
    

    @Override
    public void send(Connection c) throws IOException {
        if(options.isEmpty()){
            // TODO: log error
            return;
        }
        c.writeLine("ASK RADIO "+(new Integer(id)).toString());
        if(message != null && !"".equals(message)){
            String[] splitted = message.split(System.lineSeparator());
            for(String line:splitted){
                c.writeLine("MSG "+line);
            }
        }
        for(Option option:options){
            c.writeLine("ITEM "+option.getMessage());
        }
        c.writeLine(".");
    }

    @Override
    public void addReply(Connection source, String[] reply) {
        try{
            String[] splitted = reply[0].split(" ");
            if(!"REPLY".equals(splitted[0]) || !"RADIO".equals(splitted[1]) || !"ITEM".equals(splitted[3])){
                // TODO: log error
            }
            
            final Integer replyOrder = (new Integer(splitted[4]))-1;
            replies.put(source, replyOrder);
            
            Object[] row = { source, options.get(replyOrder) };
            tableModel.addRow(row);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    options.get(replyOrder).getCounter().inc();
                }
            });
            
        }catch(IndexOutOfBoundsException | NumberFormatException e){
            // TODO: log error
        }
    }

    @Override
    public String getShortDesc() {
        if(this.message != null && !"".equals(this.message)){
            return "Mož: "+this.message;
        }else{
            return "Mož: "+ date.get(Calendar.HOUR_OF_DAY)+":"+date.get(Calendar.MINUTE);
        }
    }

    @Override
    public String toString() {
        return this.getShortDesc();
    }
    
    

    @Override
    public void setId(int id) {
        this.id = id;
    }

    @Override
    public int getId() {
        return this.id;
    }

    @Override
    public Container getContainer() {
        if(container == null){
            setupContainer();
        }
        return container;
    }
    
    private void setupContainer(){
        container = new JPanel();
        JTable table = new JTable(tableModel);
        table.setPreferredSize(new Dimension(0, 200));
        container.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.insets = new Insets(10, 10, 10, 10);
        c.anchor = GridBagConstraints.NORTHWEST; c.fill = GridBagConstraints.HORIZONTAL;
        container.add(table, c);
        c.gridy = 1; c.gridwidth = 2; c.insets = new Insets(0, 10, 0, 0);
        c.gridx = 0;
        c.fill = GridBagConstraints.NONE;
        container.add(new JLabel("<html><b>Součty odpovědí: </b></html>"), c);
        c.gridwidth = 1;
        for(int i = 0; i < options.size(); i++){
            Option o = options.get(i);
            if(i == options.size() - 1){
                c.weighty = 1;
            }
            c.gridx = 0; c.weightx = 0; c.gridy++;
            container.add(new JLabel(o.toString()+": "), c);
            c.gridx = 1; c.weightx = 1;
            container.add(o.getCounter(), c);
        }
    }
    
    /**
     * Reprezentuje jednu z možností. Zároveň obsahuje počítadlo,
     * které počítá kolik lidí již na otázku odpovědělo touto možností.
     */
    private static class Option{
        /// pořadí této možnosti. Musí být unikátní.
        private int order;
        /// text této možnosti
        private String message;
        /// počítadlo, upravený JLabel
        private JLabelCounter counter;

        public Option(int order, String message) {
            this.message = message;
            this.order = order;
            this.counter = new JLabelCounter();
        }
        
        public int getOrder(){
            return this.order;
        }
        
        public JLabelCounter getCounter(){
            return this.counter;
        }
        
        /**
         * Vrací text této možnosti, tj řetězec předaný v konstruktoru.
         * @return Řetězec předaný v konstruktoru.
         */
        public String getMessage(){
            return this.message;
        }

        /**
         * Vrací textovou reprezentaci této možnosti. Hodí se k zobrazení v GUI.
         * @return Textová reprezentace této možnosti.
         */
        @Override
        public String toString() {
            return this.message;
        }
    }
    
    private int id = -1;
    private ArrayList<Option> options = new ArrayList<>();
    private String message = "";
    private Map<Connection, Integer> replies = new HashMap<>();
    private Calendar date = Calendar.getInstance();
    
    
    private JPanel container;
    private ReadOnlyTableModel tableModel = new ReadOnlyTableModel();
}
